/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from "react";
import { connect } from "dva";
import {
  Input,
  Button,
  message,
  Empty,
  Divider,
  Card,
  Avatar,
  Table,
  Spin,
  Row,
  Col,
  Select,
  Modal,
} from "antd";
import { debounce } from "lodash";
import PageHeaderLayout from "@/layouts/PageHeaderLayout";
import StandardSelect from "@/components/Select";
import { check } from "@/components/_utils";
import ExpressModal from "@/components/ExpressModal";
import { dateCalendar } from "@/utils/utils";
import router from "umi/router";
import KbPreviewImage from "@/components/KbPreviewImage";
import moment from "moment";
import styles from "./Search.less";

const CardMeta = Card.Meta;
const InputSearch = Input.Search;
const { Option } = Select;

const wayBillTypeMap = {
  6: "send",
  5: "arrive",
  2: "delivery",
  3: "sign",
  4: "error",
};
const jumpType = Object.keys(wayBillTypeMap);

@connect(({ loading, advanced, report, setting }) => ({
  ...setting,
  advanced,
  report,
  searching: loading.effects["advanced/search"],
  getting: loading.effects["advanced/searchDetail"],
  operating: loading.effects["report/getYzList"],
}))
export default class Advanced extends Component {
  handleSearch = debounce(
    value => {
      value = value.trim();
      const { currentIndex } = this.state;
      const { key, reg } = this.selects[currentIndex];
      const { code, msg } = check({
        form: {
          [key]: {
            reg,
            value,
          },
        },
      });
      if (code > 0) {
        message.error(msg);
        return;
      }
      const { dispatch } = this.props;
      dispatch({
        type: "advanced/search",
        payload: {
          type: key,
          keyword: value,
          // cm_id: new_value.join()
        },
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  constructor(props) {
    super(props);
    this.state = {
      currentIndex: "0",
      value: [],
      newList: [],
      scrollPage: 0,
    };
    this.selects = [
      { index: "0", name: "单号", key: "1", reg: "waybillNum" },
      { index: "1", name: "取件码", key: "2", reg: "bh" },
      { index: "2", name: "手机号", key: "3", reg: "phone" },
    ];
    this.yzColumns = [
      {
        title: "时间",
        dataIndex: "create_time",
        width: "25%",
        render: dateCalendar,
      },
      {
        title: "类型",
        dataIndex: "desc",
        width: "25%",
        render: (text, record) => {
          const { picture, picture_invalid } = record;
          if (picture_invalid === "" || picture_invalid === undefined) {
            return <span style={{ marginRight: 10 }}>{text}</span>;
          }

          if (picture_invalid == 1) {
            return (
              <>
                <span style={{ marginRight: 10 }}>{text}</span>
                <Avatar shape="square" size="large" onClick={this.onNoPictureClick} />
              </>
            );
          }

          return (
            <>
              <span style={{ marginRight: 10 }}>{text}</span>
              {picture && <KbPreviewImage src={picture} />}
            </>
          );
        },
      },
      {
        title: "驿站",
        dataIndex: "inn_name",
        width: "25%",
      },
      {
        title: "操作员",
        dataIndex: "operator",
        width: "25%",
      },
    ];
    this.gpColumns = brand => [
      {
        title: "时间",
        dataIndex: "create_time",
        width: "25%",
        render: create_time => {
          return dateCalendar(create_time, true);
        },
      },
      {
        title: "类型",
        dataIndex: "desc",
        width: "25%",
        render: (desc, record) => {
          const {
            waybill_type,
            waybill_type_text,
            picture,
            picture_invalid,
            operator_phone,
            operator,
            create_time,
            waybill_no,
          } = record;
          const text = desc || waybill_type_text;

          const Text = () =>
            jumpType.includes(waybill_type) ? (
              <a
                onClick={() =>
                  this.onJump(wayBillTypeMap[waybill_type], {
                    brand,
                    phone: operator_phone || operator,
                    time: create_time,
                    waybill_no,
                  })
                }
              >
                {text}
              </a>
            ) : (
              <>{text}</>
            );
          if (picture_invalid === "" || picture_invalid === undefined) {
            return (
              <span style={{ marginRight: 10 }}>
                <Text />
              </span>
            );
          }

          if (picture_invalid == 1) {
            return (
              <>
                <span style={{ marginRight: 10 }}>
                  <Text />
                </span>
                <Avatar shape="square" size="large" onClick={this.onNoPictureClick} />
              </>
            );
          }

          return (
            <>
              <span style={{ marginRight: 10 }}>
                <Text />
              </span>
              {picture && <KbPreviewImage src={picture} />}
            </>
          );
        },
      },
      {
        title: "类型对象",
        dataIndex: "waybill_type",
        width: "25%",
        render: (waybill_type, record) => {
          const {
            inn_name,
            next_station_name,
            sign_man,
            bad_waybill_type,
            delivery_phone,
            delivery_name,
          } = record;
          switch (waybill_type) {
            case "2":
              return `派件员：${delivery_name || ""} ${delivery_phone || ""}`;
            case "3":
              return `签收人：${sign_man || ""}`;
            case "4":
              return `问题件类型：${bad_waybill_type || ""}`;
            case "5":
              return "";
            case "6":
              return `下一站：${next_station_name || ""}`;
            default:
              return `驿站：${inn_name || ""}`;
          }
        },
      },
      {
        title: "操作员",
        dataIndex: "operator",
        width: "25%",
        render: (operator, record) => {
          const { operator_phone } = record;
          return `快递员：${operator_phone || ""}`;
        },
      },
    ];
  }

  onJump = (hash, { brand, phone, time, waybill_no }) => {
    const timeFormat = moment(time).format("YYYY-MM-DD");
    if (hash && brand) {
      router.push({
        pathname: "/Allocation/GunScanRecord",
        hash: `#${hash}`,
        query: {
          brand,
          courier: phone,
          cm_phone: phone,
          start_scan_time: timeFormat,
          end_scan_time: timeFormat,
          waybill_no,
        },
      });
    }
  };

  onNoPictureClick = () => {
    Modal.info({
      title: "该底单照片已过期，你可扩充云存储空间后查看",
    });
  };

  componentDidMount = () => {
    this.scrollPage = 1;
    this.setState({
      scrollPage: 0,
    });
  };

  handleSelectChange = currentIndex => {
    this.setState({
      currentIndex,
    });
  };

  // 展示物流
  showExpressModal = data => {
    const { brand, brand_cn, waybill_no } = data;
    this.setState({
      expressInfo: {
        brand,
        waybill_no,
        brand_name: brand_cn,
      },
    });
  };

  handleChange = (val, label, extra) => {
    const new_value = [];
    label.map(({ key }) => {
      new_value.push(key);
    });
    if (val.length > 5) {
      this.setState({
        value: val.slice(0, 5),
      });
      message.error("最多只能选择5家驿站！");
    } else {
      this.setState({ value: val, new_value });
    }
  };

  // 筛选
  onFilterOption = (inputValue, options) => {
    const { children, value } = options.props;
    if (children.indexOf(inputValue) >= 0) return true;
  };

  // 分页分组
  group = (array, subGroupLength) => {
    let index = 0;
    const newArray = [];
    while (index < array.length) {
      newArray.push(array.slice(index, (index += subGroupLength)));
    }
    return newArray;
  };

  // 下拉列表滚动
  onPopupScroll = e => {
    const {
      report: { yzList },
    } = this.props;
    const { newList } = this.state;
    e.persist();
    const { target } = e;
    const scrollPageNum = 100;
    if (target.scrollTop + target.offsetHeight >= target.scrollHeight) {
      if (!this.filterOption && newList.length < yzList.length) {
        this.scrollPage++;
        this.setState(
          {
            newList: yzList.slice(0, this.scrollPage * scrollPageNum),
          },
          () => {
            if (newList.length < yzList.length) {
              setTimeout(() => {
                [...target.getElementsByTagName("li")][
                  (this.scrollPage - 1) * scrollPageNum - 3
                ].scrollIntoView();
              }, 0.1);
            }
          }
        );
      }
    }
  };

  // 下拉获取焦点
  onFocusScroll = () => {
    const {
      report: { yzList },
    } = this.props;
    this.scrollPage = 1;
    this.filterOption = false;
    this.setState({
      newList: yzList.slice(0, this.scrollPage * 100),
    });
  };

  // 输入搜索
  onSearchScroll = val => {
    const {
      report: { yzList },
    } = this.props;
    if (val == "") {
      this.filterOption = false;
    } else {
      this.filterOption = true;
    }
    this.setState({
      newList: yzList,
    });
  };

  // 展示详情
  showDetail(data, index) {
    const { dispatch } = this.props;
    const { cm_id, dak_id, brand, waybill_no: waybill, id } = data;
    this.activeId = id;
    dispatch({
      type: "advanced/searchDetail",
      payload: {
        cm_id: cm_id || dak_id, // 兼容共配数据
        waybill,
        brand,
      },
      index,
    });
  }

  render() {
    const { currentIndex, expressInfo, value, newList } = this.state;
    const {
      getting,
      searching,
      advanced: { result },
    } = this.props;
    const searchButton = (
      <Button type="primary" loading={searching} icon="search">
        查询
      </Button>
    );
    const searchSelect = (
      <StandardSelect
        style={{ width: 90 }}
        onChange={this.handleSelectChange}
        value={currentIndex}
        kkey="index"
        options={this.selects}
      />
    );

    const children = [];
    newList.map(({ cm_id, company_name, id }, index) => {
      children.push(
        <Option key={`${cm_id}`} value={id}>
          {company_name}
        </Option>
      );
    });

    return (
      <PageHeaderLayout title="超级搜索">
        <div className={styles.main}>
          <div className={styles.searchBar}>
            <div>
              <span style={{ display: "inline-block", width: "70px", marginRight: "15px" }} />
              <InputSearch
                defaultValue={result ? result.waybill_no : null}
                style={{ maxWidth: 600 }}
                maxLength={40}
                enterButton={searchButton}
                addonBefore={searchSelect}
                onSearch={this.handleSearch}
                placeholder={`请输入${this.selects[1 * currentIndex].name}`}
              />
            </div>
          </div>
          <div className={styles.searchContent}>
            <Spin spinning={!!searching}>
              {result ? (
                result.map((item, index) => {
                  return (
                    <div key={item.id} className={styles.card}>
                      <Card>
                        <CardMeta
                          avatar={
                            <Avatar
                              src={`https://img.kuaidihelp.com/brand_logo/icon_${item.brand}.png`}
                            />
                          }
                          title={
                            <div>
                              <span>{item.brand_cn}</span>
                              <a
                                style={{ margin: "0 16px" }}
                                onClick={this.showExpressModal.bind(this, item)}
                              >
                                {item.waybill_no}
                                {">>"}
                              </a>
                              <span style={{ color: "#999" }}>{item.status_cn}</span>
                            </div>
                          }
                          description={
                            <Row>
                              <Col sm={18}>
                                <span>
                                  <span>客户电话：</span>
                                  {item.phone}
                                  <span style={{ marginLeft: 16 }}>取件码：</span>
                                  {item.pickup_code}
                                </span>
                              </Col>
                              <Col sm={6} style={{ textAlign: "right" }}>
                                {!item.operates && (
                                  <span style={{ display: "inline-block" }}>
                                    <Spin
                                      size="small"
                                      spinning={!!(getting && this.activeId === item.id)}
                                    >
                                      <a onClick={this.showDetail.bind(this, item, index)}>
                                        查看操作记录
                                      </a>
                                    </Spin>
                                  </span>
                                )}
                              </Col>
                            </Row>
                          }
                        />
                      </Card>
                      {item.operates && (
                        <>
                          <Divider style={{ marginTop: 30 }} orientation="left">
                            驿站操作记录
                          </Divider>
                          <Table
                            columns={this.yzColumns}
                            dataSource={item.operates}
                            rowKey="create_time"
                            pagination={false}
                          />
                        </>
                      )}
                      {item.gpRecords && (
                        <>
                          <Divider style={{ marginTop: 30 }} orientation="left">
                            共配操作记录
                          </Divider>
                          <Table
                            columns={this.gpColumns(item.brand)}
                            dataSource={item.gpRecords}
                            rowKey="create_time"
                            pagination={false}
                          />
                        </>
                      )}
                    </div>
                  );
                })
              ) : (
                <Empty mode="small" />
              )}
            </Spin>
          </div>
          <ExpressModal
            cleanData={() => {
              this.setState({
                expressInfo: null,
              });
            }}
            data={expressInfo}
          />
        </div>
      </PageHeaderLayout>
    );
  }
}
